package com.sws.worktive.volley;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.RequestQueue.RequestFilter;
import com.android.volley.toolbox.Volley;


public class MyVolley {
	
	//singleton
	private MyVolley(){}

	private static MyVolley mMyVolley;
	
	private RequestQueue mRequestQueue;
	
	public static final String TAG = Application.class.getSimpleName();
	
	

	//MyVolley is a singleton class and it always holds only one Request Queue Object as it is 
	//suggested here http://www.androidhive.info/2014/05/android-working-with-volley-library-1/.
	public static MyVolley getMyVolley(Context context){
		if (mMyVolley == null) {
			mMyVolley = new MyVolley();
			mMyVolley.initRequestQueue(context);
		}
		
		return mMyVolley;
	}
	
	//initialize a requestQueue from Volley
	private void initRequestQueue(Context context){
		mRequestQueue = Volley.newRequestQueue(context);
	}
	
	//get the request queue. Throw an exception if it is not initialized
	public RequestQueue getRequestQueue() {
        if (mRequestQueue != null) {
            return mRequestQueue;
        } else {
            throw new IllegalStateException("RequestQueue not initialized");
        }
    }
	
	//add request to the queue with a tag, you can use the tag to cancel the request.
	public <T> void addToRequestQueue(Request<T> req, String tag) {
		req.setShouldCache(false);
		// set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }
 
	//add request to the queue with default tag
    public <T> void addToRequestQueue(Request<T> req) {
    	req.setShouldCache(false);
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
    
    //cancel all the pending requests
    public void cancelPendingRequest() {
    	getRequestQueue().cancelAll(TAG);
    }
    
    //cancel specific request associate with a tag
    public void cancelRequestWithTag(String tag) {
    	getRequestQueue().cancelAll(tag);
    }
    
    //cancel all the requests
    public void cancelAllRequest() {
    	getRequestQueue().cancelAll(new RequestFilter() {
			@Override
			public boolean apply(Request<?> request) {
				return true;
			}
		});
    }
	
}
